﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SharpShare.Storage {
    public class StreamStorageDataProvider : IStorageDataProvider {
        private object _synclock = new object();

        public StreamStorageDataProvider(Stream stream ) {
            this.Stream = stream;
        }

        public Stream Stream { get; private set; }

        #region IStorageDataProvider Members

        public long Length {
            get { return this.Stream.Length; }
        }

        public StorageFileAccess AccessMode {
            get {
                StorageFileAccess access = StorageFileAccess.None;

                if (this.Stream.CanRead) {
                    access |= StorageFileAccess.Read;
                }
                if (this.Stream.CanWrite) {
                    access |= StorageFileAccess.Write;
                }

                return access;
            }
        }

        public int Read(long position, byte[] buffer, int offset, int length) {
            lock (_synclock) {
                this.Stream.Position = position;
                return this.Stream.Read(buffer, offset, length);
            }
        }

        public void Write(long position, byte[] buffer, int offset, int length) {
            lock (_synclock) {
                this.Stream.Position = position;
                this.Stream.Write(buffer, offset, length);
            }
        }

        public void SetLength(long length) {
            lock (_synclock) {
                this.Stream.SetLength(length);
            }
        }

        public void Flush(bool synchronize) {
            lock (_synclock) {
                this.Stream.Flush();
            }
        }

        public virtual void Close() {
            this.Stream.Close();
        }

        #endregion
    }
}
